import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
// import iView from 'iview'

import ViewUI from 'view-design'
import { Message } from 'view-design'
// import { SysAreaApi } from '@/api/SysArea.api.js'
import { setClientToken, getToken, canTurnTo, setTitle } from '@/libs/util'

import userApi from '@/api/user'
import config from '@/config'
const { homeName } = config

Vue.use(Router)
const router = new Router({
  routes,
  mode: 'history',
  // base: '/b/',
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})
const LOGIN_PAGE_NAME = 'login'

const turnTo = (to, access, next) => {
  if (canTurnTo(to.name, access, routes)) next() // 有权限，可访问
  else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
}

router.beforeEach((to, from, next) => {
  ViewUI.LoadingBar.start()
  // store.dispatch('getLodinStatus', res.data)
  console.log('⭐ to: ', to)
  console.log('⭐ from: ', from)
    if (to.query.token && !to.query.clientid) {
      let token = to.query.token
      console.log('🐷🐷！！！！！！！！！！！')
      userApi.vxLogin({
        'Authorization': 'Bearer ' + token
      }).then(res => {
        const data = res.data
        console.log('😭！！！！！！！！！！！')
        if (data.success) {
          setClientToken(token)
          localStorage.setItem('clientLoginInfo', JSON.stringify(data))
          next({
            name: to.name
          })
        }
      })
    } else if (to.query.stats) {
      userApi.LoginAxsUser({
        code: to.query.code,
        scope: to.query.scope
      }).then(res => {
        const data = res.data
  
        if (data.success) {
          setClientToken(data.data.access_token)
          localStorage.setItem('clientLoginInfo', JSON.stringify(data))
          next({
            name: homeName
          })
        } else {
          
          next({
            name: 'error_message',
            query: {
              message: data.message
            }
          })
        }
      })
    } else if (to.query.clientid) {
      console.log(to.query)
      userApi.axLoginTokenOauth({
        ClientId: to.query.clientid,
        ClientSecret: to.query.clientsecret,
        Token: to.query.token
      }).then(res => {
        console.log('*****(((((((')
        const data = res.data
        console.log(data)
  
        if (data.success) {
          setClientToken(data.data.access_token)
          localStorage.setItem('clientLoginInfo', JSON.stringify(data))
          next({
            name: homeName
          })
        } else {
          
          next({
            name: 'third_party_login',
            query: {
              // message: data.message,
              uken: to.query.uken,
              clientId: to.query.clientid,
              clientSecret: to.query.clientsecret
            }
          })
        }
      })
    } else {
      const token = getToken()
      if (!token && to.name !== LOGIN_PAGE_NAME) {
        console.log('👀·············')
        // 未登录且要跳转的页面不是登录页
        if(to.name === 'error_message') {
          next()
        } else if (to.name === 'third_party_login') {
          next()
        } else {
          next({
            name: LOGIN_PAGE_NAME // 跳转到登录页
          })
        }
      } else if (!token && to.name === LOGIN_PAGE_NAME) {
        // 未登陆且要跳转的页面是登录页
        next() // 跳转
      } else if (token && to.name === LOGIN_PAGE_NAME) {
        // 已登录且要跳转的页面是登录页
        // loginCheck()
        next({
          name: homeName // 跳转到homeName页
        })
      } else {
        store.dispatch('getLodinStatus').then(val => {
          console.log(val)
          if (val.success) {
            if (to.meta.access && to.meta.access[0]) {
              store.dispatch('getUserInfo', { data: to.meta.access[0] })
            } else {
              store.dispatch('getUserInfo', { data: false })
            }
            turnTo(to, store.state.user.access, next)
          } else {
            setClientToken('')
            setTimeout(() => {
              next({
                name: LOGIN_PAGE_NAME // 跳转到登录页
              })
            }, 3000)
          }
        })
      }
    }
})

router.afterEach(to => {
  ViewUI.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
